﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;


namespace lxwmvc
{
    /// <summary>
    /// 云图和云图点金，记录用户ID和用户名用这个方法可以共享cookies
    /// </summary>
    public class yuntucookieshelper
    {        
        const string cookiesqianzhun = "_lxw_";
        const string domain = ".yunto.cc";

        public static string yonghuid
        {
            get
            {
                return yuntucookieshelper.get("yonghuid");
            }
            set
            {
                yuntucookieshelper.set("yonghuid", value);
            }
        }

        public static string loginname
        {
            get
            {
                return yuntucookieshelper.get("loginname");
            }
            set
            {
                yuntucookieshelper.set("loginname", value);
            }
        }

        /// <summary>
        /// 这里需要注意，写入并且马上读取的时候，cookie是绝对不允许。
        /// </summary>
        /// <param name="strcookieskey"></param>
        /// <param name="strcookiesvalue"></param>
        public static void set(string strcookieskey, string strcookiesvalue)
        {            
            string strpre = domain + "_" + HttpContext.Current.Request.Url.Port;
            //本地考虑 本地端口一般不用80
            if (HttpContext.Current.Request.Url.Port != 80)
                strpre = HttpContext.Current.Request.Url.Host + "_" + HttpContext.Current.Request.Url.Port;
         

            strpre = strpre.Replace(".", "_");

            strcookieskey = cookiesqianzhun + strpre + strcookieskey;
            HttpCookie cookies = new HttpCookie(strcookieskey, HttpUtility.UrlEncode(strcookiesvalue));

            cookies.Domain = domain;
            cookies.Secure = false;


            cookies.Expires = DateTime.Now.AddYears(1);
            HttpContext.Current.Response.Cookies.Remove(cookies.Name);
            HttpContext.Current.Response.SetCookie(cookies);

            HttpContext.Current.Session[strcookieskey] = strcookiesvalue;
        }

        public static string get(string strcookieskey)
        {
            string strpre = domain + "_" + HttpContext.Current.Request.Url.Port;
            //本地考虑 本地端口一般不用80
            if (HttpContext.Current.Request.Url.Port != 80)
                strpre = HttpContext.Current.Request.Url.Host + "_" + HttpContext.Current.Request.Url.Port;
            strpre = strpre.Replace(".", "_");

            strcookieskey = cookiesqianzhun + strpre + strcookieskey;
            if (HttpContext.Current.Session[strcookieskey] != null)
                return HttpContext.Current.Session[strcookieskey].ToString();

            if (HttpContext.Current.Request.Cookies[strcookieskey] != null)
            {
                return HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request.Cookies[strcookieskey].Value);
            }

            return "";
        }
    }
}
